<?php 
    require_once ("/mnt/sdcard/www/Includes/simplecms-config.php");
    require_once  ("/mnt/sdcard/www/Includes/connectDB.php");
    include("/mnt/sdcard/www/Includes/header.php");

    $sessionName = $_SESSION['name'];
    $sessionUserID = $_SESSION['userid'];

    define(CABLE_NONE, 0);
    define(CABLE_USB, 1);
    define(CABLE_CHARGER, 2);
    define(CABLE_USB_CHARGER, 3);

    define(APPROVAL_LEND, 1);
    define(APPROVAL_CONTINUE, 2);
    define(APPROVAL_RETURN, 0);

    define(STATE_AFTER_APPROVAL, 0);
    define(STATE_APPROVAL, 1);
    define(STATE_REJECT, 2);
    define(STATE_ALL, 3);

    if (!logged_on())
    {
        echo "
            <div class='alert alert-danger'>
                <strong>접근 오류!</strong> 로그인 후에 이용할 수 있는 서비스 입니다.
            </div>
        ";
    }

    $searchType = 3;

    if(isset($_POST['search']))
    {
        $searchType = $_POST['searchType'];
    }

    $page = 1;

    if(isset($_GET['page']))
    {
        $page = $_GET['page'];
        $searchType = $_GET['searchType'];
    }

    if($_GET['approval'] == STATE_APPROVAL && is_admin())
    {
        //approval=1&approvalID=$approval_id&deviceID=$device_id&userID=$user_id&cable=$cable&startDate=$start_date&endDate=$end_date&approvalType=$approval_type
        $approval = $_GET['approval'];
        $approvalID = $_GET['approvalID'];
        $deviceID = $_GET['deviceID'];
        $userID = $_GET['userID'];
        $cable = $_GET['cable'];
        $startDate = $_GET['startDate'];
        $endDate = $_GET['endDate'];
        $approvalType = $_GET['approvalType'];
        $searchType = $_GET['searchType'];

        //////////////////////////////////////////////////////////////////////////////////////////////////////////
        // 대여승인 하는 기기가 이미 대여 중인지를 확인
        if($approvalType == APPROVAL_LEND)
        {
            $query = "SELECT device_id FROM users_lend WHERE device_id='$deviceID' and returned='0'";
            $statement_users_lend = $databaseConnection->prepare($query);
            $statement_users_lend->execute();
            $statement_users_lend->store_result();

            if($statement_users_lend->affected_rows > 0)
            {
                $statement_users_lend->close();
                echo("
                    <script>
                    window.alert('이미 승인되어 대여중인 기기입니다.')
                    location.replace('approval.php')
                    </script>
                ");
                exit;
            }
        }
        //////////////////////////////////////////////////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////////////////////////////////////////////////
        // 승인 처리
        $query = "UPDATE approval set approval_state='$approval', approval_date=Now(), approval_user_id='$sessionName' WHERE approval_id='$approvalID'";
        $statement_approval = $databaseConnection->prepare($query);
        $statement_approval->execute();
        $statement_approval->store_result();
        //////////////////////////////////////////////////////////////////////////////////////////////////////////

        ///////////////////////////////////////////////////////////////////////
        // 승인 타입에 맞게 DB 변경
        switch ($approvalType) {
            case APPROVAL_LEND:
                $returned = 0;

                $query = "UPDATE deviceInfo set team=(SELECT team FROM users WHERE id='$userID'), name=(SELECT name FROM users WHERE id='$userID'), startDate='$startDate', endDate='$endDate', deviceState='$approvalType' WHERE id='$deviceID'";
                $statement_deviceInfo = $databaseConnection->prepare($query);
                $statement_deviceInfo->execute();
                $statement_deviceInfo->store_result();

                $query = "INSERT INTO users_lend (device_id, user_id, cable, date, returnedDate, returned) VALUES (?, ?, ?, Now(), '', ?)";
                $statement_users_lend = $databaseConnection->prepare($query);
                $statement_users_lend->bind_param('iiii', $deviceID, $userID, $cable, $returned);
                $statement_users_lend->execute();
                $statement_users_lend->store_result();

                $creationWasSuccessful = ($statement_approval->affected_rows == 1 ? true : false) && ($statement_deviceInfo->affected_rows == 1 ? true : false) && ($statement_users_lend->affected_rows == 1 ? true : false);
                break;

            case APPROVAL_CONTINUE:
                $returned = 0;

                $query = "UPDATE deviceInfo set endDate='$endDate' WHERE id='$deviceID'";
                $statement_deviceInfo = $databaseConnection->prepare($query);
                $statement_deviceInfo->execute();
                $statement_deviceInfo->store_result();

                $creationWasSuccessful = ($statement_approval->affected_rows == 1 ? true : false) && ($statement_deviceInfo->affected_rows == 1 ? true : false);
                break;

            case APPROVAL_RETURN:
                $returned = 1;
                $startDate = "0000-00-00";

                $query = "UPDATE deviceInfo set team=(SELECT team FROM users WHERE id='$sessionUserID'), name=(SELECT name FROM users WHERE id='$sessionUserID'), startDate='$startDate', endDate='$endDate', deviceState='$approvalType' WHERE id='$deviceID'";
                $statement_deviceInfo = $databaseConnection->prepare($query);
                $statement_deviceInfo->execute();
                $statement_deviceInfo->store_result();

                $query = "UPDATE users_lend set returnedDate=Now(), returned='1' WHERE device_id='$deviceID' AND returned='0'";
                $statement_users_lend = $databaseConnection->prepare($query);
                $statement_users_lend->execute();
                $statement_users_lend->store_result();

                $creationWasSuccessful = ($statement_approval->affected_rows == 1 ? true : false) && ($statement_deviceInfo->affected_rows == 1 ? true : false) && ($statement_users_lend->affected_rows == 1 ? true : false);
                break;
        }
        ///////////////////////////////////////////////////////////////////////

        if ($creationWasSuccessful)
        {
            switch ($approvalType) {
                case APPROVAL_RETURN:
                    // 같은 device_id를 가진 승인 대기 건이 있는지 확인
                    // 대여가능/결재진행중 중에 어떤 값으로 deviceState를 설정할지 체크
                    $query = "SELECT * FROM approval WHERE device_id='$deviceID' and approval_state='0'";
                    $statement = $databaseConnection->prepare($query);
                    $statement->execute();
                    $statement->store_result();

                    
                    if($statement->affected_rows > 0)
                    {
                        $query = "UPDATE deviceInfo set deviceState='3' WHERE id='$deviceID'";
                        $statement = $databaseConnection->prepare($query);
                        $statement->execute();
                        $statement->store_result();
                    }
                    break;
            }
            //$statement->close();
            echo("
                <script>
                window.alert('승인처리 되었습니다.')
                location.replace('approval.php')
                </script>
            ");
            exit;
        }
        else
        {
            //$statement->close();
            echo("
                <script>
                window.alert('실패했습니다.')
                location.replace('approval.php')
                </script>
            ");
            exit;
        }
    }
    else if($_GET['approval'] == STATE_REJECT && is_admin())
    {
        // 반려일 경우, deviceInfo의 deviceState 컬럼을 변경
        // 자세한 케이스 확인 필요
        $approval = $_GET['approval'];
        $approvalID = $_GET['approvalID'];
        $deviceID = $_GET['deviceID'];
        $approvalType = $_GET['approvalType'];
        $searchType = $_GET['searchType'];

        //////////////////////////////////////////////////////////////////////////////////////////////////////////
        // 반려처리
        $query = "UPDATE approval set approval_state='2', approval_date=Now(), approval_user_id='$sessionName' WHERE approval_id='$approvalID'";
        $statement = $databaseConnection->prepare($query);
        $statement->execute();
        $statement->store_result();
        //////////////////////////////////////////////////////////////////////////////////////////////////////////

        $creationWasSuccessful = $creationWasSuccessful || ($statement->affected_rows == 1 ? true : false);

        if ($creationWasSuccessful)
        {
            switch ($approvalType) {
                case APPROVAL_LEND:
                    // 같은 device_id를 가진 승인 대기 건이 있는지 확인
                    // 대여가능/결재진행중 중에 어떤 값으로 deviceState를 설정할지 체크
                    $query = "SELECT * FROM approval WHERE device_id='$deviceID' and approval_state='0'";
                    $statement = $databaseConnection->prepare($query);
                    $statement->execute();
                    $statement->store_result();

                    if($statement->affected_rows == 0)
                    {
                        $query = "UPDATE deviceInfo set deviceState='0' WHERE id='$deviceID'";
                        $statement = $databaseConnection->prepare($query);
                        $statement->execute();
                        $statement->store_result();
                    }
                    break;
            }
            $statement->close();
            echo("
                <script>
                window.alert('반려처리 되었습니다.')
                location.replace('approval.php')
                </script>
            ");
            exit;
            //header ("Location: phoneList.php");
        }
        else
        {
            $statement->close();
            echo("
                <script>
                window.alert('실패했습니다.')
                location.replace('approval.php')
                </script>
            ");
            exit;
        }
    }
?>

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
            <?php
                if (logged_on())
                {
                    $url = "/phoneList.php";
                }
                else
                {
                    $url = "/index.php";
                }
            ?>
            <a class="navbar-brand" href="<?php echo $url ?>">Device Management System</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="/index.php">Home</a></li>
                <?php
                    if (logged_on())
                    {
                        echo '
                            <li><a href="/phoneList.php">기기목록</a></li>
                            <li class="active"><a href="/approval.php">결재</a></li>
                        ';
                    }
                ?>
                <?php
                    if (is_admin())
                    {
                        echo '
                            <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">관리메뉴<b class="caret"></b></a>
                                <ul class="dropdown-menu">
                                    <li><a href="/phoneEnroll.php">기기등록</a></li>
                                    <li><a href="/manage.php">기기관리</a></li>
                                    <!--<li class="divider"></li>
                                    <li class="dropdown-header">Nav header</li>
                                    <li><a href="#">Separated link</a></li>
                                    <li><a href="#">One more separated link</a></li>-->
                                </ul>
                            </li>
                        ';
                    }
                ?>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <?php
                    if (logged_on())
                    {
                        if (is_admin())
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(관리자)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";
                        }
                        elseif (is_member())
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(정회원)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";   
                        }
                        else
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(준회원)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";
                        }
                    }
                    else
                    {
                        echo "
                            <form action='index.php' method='post' class='navbar-form navbar-right'>
                                <div class='form-group'>
                                    <input type='text' name='username' placeholder='아이디' class='form-control'>
                                </div>
                                <div class='form-group'>
                                    <input type='password' name='password' placeholder='비밀번호' class='form-control'>
                                </div>
                                <button type='submit' name='submit' class='btn btn-success'>로그인</button>
                            </form>
                        ";
                    }
                ?>
            </ul>
        </div><!--/.navbar-collapse -->
    </div>
</div>

<!-- 본문 시작 -->
<div class="container">
    <p>
    <form action="approval.php" method="post" class="form-inline" role="form">
        <div class="form-group">
            <select name="searchType" class="form-control">
                <option value="3" <? if($searchType == STATE_ALL) { echo "selected"; } ?>>전체</option>
                <option value="0" <? if($searchType == STATE_AFTER_APPROVAL) { echo "selected"; } ?>>결재전</option>
                <option value="1" <? if($searchType == STATE_APPROVAL) { echo "selected"; } ?>>승인</option>
                <option value="2" <? if($searchType == STATE_REJECT) { echo "selected"; } ?>>반려</option>
            </select>
        </div>
        <div class="form-group">
            <button type="submit" name="search" class="btn btn-primary">조회하기</button>
        </div>
    </form>
    </p>

    <!-- 시작: 페이지네이션 -->
    <?php

        // 전체 레코드 수를 얻어옴
        if(is_admin())
        {
            $query = "SELECT * FROM approval";

            switch ($searchType) {
                case STATE_ALL:
                    break;
                case STATE_AFTER_APPROVAL:
                    $query .= " WHERE approval_state='0'";
                    break;
                case STATE_APPROVAL:
                    $query .= " WHERE approval_state='1'";
                    break;
                case STATE_REJECT:
                    $query .= " WHERE approval_state='2'";
                    break;
            }
        }
        elseif(logged_on())
        {
            $query = "SELECT * FROM approval";

            switch ($searchType) {
                case STATE_ALL:
                    $query .= " WHERE user_id=$sessionUserID";
                    break;
                case STATE_AFTER_APPROVAL:
                    $query .= " WHERE approval_state='0' and user_id=$sessionUserID";
                    break;
                case STATE_APPROVAL:
                    $query .= " WHERE approval_state='1' and user_id=$sessionUserID";
                    break;
                case STATE_REJECT:
                    $query .= " WHERE approval_state='2' and user_id=$sessionUserID";
                    break;
            }
        }

        $statement_page = $databaseConnection->prepare($query);
        $statement_page->execute();
        $statement_page->store_result();
        $total = $statement_page->affected_rows;
        $statement_page->close();

        // 페이징을 위한 변수 설정
        $page_per_record = 20;
        $block_per_page = 5;
        $now_page = $page; // GET으로 현재 페이지를 넘겨줄 예정
        $total_record = $total;
        
        // 페이징을 위한 변수 설정
        $total_page = ceil($total_record / $page_per_record);           // 전체 페이지 갯수
        $total_block = ceil($total_page / $block_per_page);             // 전체 블록 갯수
        $now_block = ceil($now_page / $block_per_page);                 // 현재 페이지가 속해 있는 블록 번소
        $start_record = ceil(($now_page - 1) * $page_per_record);        // 가져올 레코드 시작 번호
        $start_page = ceil(($now_block - 1) * $block_per_page) + 1;     // 가져올 페이지 시작 번호
        $end_page = (($start_page + $block_per_page) <= $total_page) ? ($start_page + $block_per_page - 1) : $total_page;

    ?>
    <!-- 끝: 페이지네이션 -->

    <?php
        if(is_admin())
        {
            //echo "admin / approvalID: " . $approvalID . ", searchType: " . $searchType;
            //echo $query;

            $query = "SELECT approval.*, users.name as users_name, deviceInfo.deviceName as device_name FROM approval, users, deviceInfo ";

            switch ($searchType) {
                case STATE_ALL:
                    $query .= "WHERE approval.user_id=users.id and approval.device_id=deviceInfo.id ";
                    break;
                case STATE_AFTER_APPROVAL:
                    $query .= "WHERE approval_state='0' and approval.user_id=users.id and approval.device_id=deviceInfo.id ";
                    break;
                case STATE_APPROVAL:
                    $query .= "WHERE approval_state='1' and approval.user_id=users.id and approval.device_id=deviceInfo.id ";
                    break;
                case STATE_REJECT:
                    $query .= "WHERE approval_state='2' and approval.user_id=users.id and approval.device_id=deviceInfo.id ";
                    break;
            }
            $query .= "ORDER BY approval_id DESC LIMIT $start_record, $page_per_record";

            $statement = $databaseConnection->prepare($query);
            $statement->execute();
            $statement->store_result();

            // approval_id, device_id, user_id, request_date, approval_date, approval_type, approval_state, start_date, end_date, cable, etc, approval_user_id
            $statement->bind_result($approval_id, $device_id, $user_id, $request_date, $approval_date, $approval_type, $approval_state, $start_date, $end_date, $cable, $etc, $approval_user_id, $users_name, 
                $device_name);
        }
        else if(logged_on())
        {
            //echo "logged_on() / approvalID: " . $approvalID[0];

            $query = "SELECT approval.*, users.name as users_name, deviceInfo.deviceName as device_name FROM approval, users, deviceInfo WHERE user_id=? ";

            switch ($searchType) {
                case STATE_ALL:
                    $query .= "and approval.user_id=users.id and approval.device_id=deviceInfo.id";
                    break;
                case STATE_AFTER_APPROVAL:
                    $query .= "and approval.user_id=users.id and approval.device_id=deviceInfo.id and approval_state='0'";
                    break;
                case STATE_APPROVAL:
                    $query .= "and approval.user_id=users.id and approval.device_id=deviceInfo.id and approval_state='1'";
                    break;
                case STATE_REJECT:
                    $query .= "and approval.user_id=users.id and approval.device_id=deviceInfo.id and approval_state='2'";
                    break;
            }
            $query .= " ORDER BY approval_id DESC LIMIT $start_record, $page_per_record";

            $statement = $databaseConnection->prepare($query);
            $statement->bind_param('i', $_SESSION['userid']);
            $statement->execute();
            $statement->store_result();

            // approval_id, device_id, user_id, request_date, approval_date, approval_type, approval_state, start_date, end_date, cable, etc
            $statement->bind_result($approval_id, $device_id, $user_id, $request_date, $approval_date, $approval_type, $approval_state, $start_date, $end_date, $cable, $etc, $approval_user_id, $users_name, 
                $device_name);
        }
        else
        {
            echo "로그인이 필요한 서비스입니다.";
        }

    ?>

    <div class="table-responsive">
    <div class="panel panel-primary">
        <div class="panel-heading">결재</div>
            <table class="table table-hover table-striped">
                <thead><tr>
                    <!-- <th><input type="checkbox" name="list[]" onclick="checkAllorNot(this)"></th> -->
                    <th class="text-center">결재번호</th>
                    <th>기기명</th>                
                    <th class="text-center">사용자</th>
                    <th class="text-center">케이블</th>
                    <th class="text-center">대여시작일</th>
                    <th class="text-center">대여종료일</th>
                    <th class="text-center">상신시간</th>
                    <th class="text-center">결재시간</th>
                    <th class="text-center">결재종류</th>
                    <th class="text-center">결재여부</th>
                    <th class="text-center">결재자</th>
                    <th>사유</th>
                </tr></thead>
            <?php 
                while($statement->fetch()) :

                    if($approval_date == "0000-00-00 00:00:00")
                    {
                        $approval_date = "";
                    }
            ?>

                <tr>
                    <td class="text-center"><?php echo $approval_id ?></td>
                    <td><?php echo $device_name ?></td>
                    <td class="text-center"><?php echo $users_name ?></td>
                    <?php
                        switch($cable)
                        {
                            case CABLE_NONE:
                                echo("<td class='text-center'>대여안함</td>");
                                break;
                            case CABLE_USB:
                                echo("<td class='text-center'>USB케이블</td>");
                                break;
                            case CABLE_CHARGER:
                                echo("<td class='text-center'>충전기</td>");
                                break;
                            case CABLE_USB_CHARGER:
                                echo("<td class='text-center'>USB케이블+충전기</td>");
                                break;
                        }
                    ?>
                    <td class="text-center"><?php echo $start_date ?></td>
                    <td class="text-center"><?php echo $end_date ?></td>
                    <td class="text-center"><?php echo $request_date ?></td>
                    <td class="text-center"><?php echo $approval_date ?></td>
                    <?php
                        switch($approval_type)
                        {
                            case APPROVAL_LEND:
                                echo("<td class='text-center'>대여신청</td>");
                                break;
                            case APPROVAL_CONTINUE:
                                echo("<td class='text-center'>연장신청</td>");
                                break;
                            case APPROVAL_RETURN:
                                echo("<td class='text-center'>반납확인</td>");
                                break;
                        }
                    ?>
                    <?php
                        switch($approval_state)
                        {
                            case STATE_AFTER_APPROVAL:
                                if(is_admin())
                                {
                                    echo("
                                        <td class='text-center'><button type=button name=approval onclick=location.href='http://210.90.237.56/approval.php?approval=1&approvalID=$approval_id&deviceID=$device_id&userID=$user_id&cable=$cable&startDate=$start_date&endDate=$end_date&approvalType=$approval_type&searchType=$searchType'; class='btn btn-xs btn-success'>승인</button>
                                        <button type=button name=approval onclick=location.href='http://210.90.237.56/approval.php?approval=2&approvalID=$approval_id&deviceID=$device_id&approvalType=$approval_type&searchType=$searchType'; class='btn btn-xs btn-danger'>반려</button>
                                    ");
                                }
                                else if(logged_on())
                                {
                                    echo("<td class='text-center'><span class='label label-info'>결재전</span></td>");
                                }
                                break;
                            case STATE_APPROVAL:
                                echo("<td class='text-center'><span class='label label-success'>승인</span></td>");
                                break;
                            case STATE_REJECT:
                                echo("<td class='text-center'><span class='label label-danger'>반려</span></td>");
                                break;
                        }
                    ?>
                    <td class="text-center"><?php echo $approval_user_id ?></td>
                    <td><?php echo $etc ?></td>
                </tr>

            <?php endwhile ?>
        </table>
    </div>
    </div>
</div>

<div class="text-center">
    <ul class="pagination">
            <?php

                if($now_block > 1)
                {
                    $prev_page = $start_page - 1;
                    echo "
                        <li><a href='http://210.90.237.56/approval.php?page=$prev_page&searchType=$searchType'>«</a></li>
                    ";
                }
                else
                {
                    echo "
                        <li class='disabled'><a href='#'>«</a></li>
                    ";
                }

                for($i=$start_page; $i<=$end_page; $i++)
                {
                    if($now_page == $i)
                    {
                        echo "
                            <li class='active'><a href='http://210.90.237.56/approval.php?page=$i&searchType=$searchType'>$i</a></li>
                        ";
                    }
                    else
                    {
                        echo "
                            <li><a href='http://210.90.237.56/approval.php?page=$i&searchType=$searchType'>$i</a></li>
                        ";
                    }
                }
                
                if($now_block < $total_block)
                {
                    $next_page = $end_page + 1;
                    echo "
                        <li><a href='http://210.90.237.56/approval.php?page=$next_page&searchType=$searchType'>»</a></li>
                    ";
                }
                else
                {
                    echo "
                        <li class='disabled'><a href='#'>»</a></li>
                    ";
                }

            ?>
    </ul>
</div>

<?php 
    include ("/mnt/sdcard/www/Includes/footer.php");
    $statement->close();
 ?>